package cool.mtc.minghe.service.service.sys.user.impl;

import cool.mtc.minghe.data.entity.sys.user.UserOrgRoleDO;
import cool.mtc.minghe.data.model.sys.user.dto.UserOrgRoleDTO;
import cool.mtc.minghe.service.mapper.sys.user.UserOrgRoleMapper;
import cool.mtc.minghe.service.service.BaseServiceImpl;
import cool.mtc.minghe.service.service.sys.user.UserOrgRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author 明河
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserOrgRoleServiceImpl extends BaseServiceImpl implements UserOrgRoleService {
    private final UserOrgRoleMapper userOrgRoleMapper;

    @Override
    public void update(long userId, List<UserOrgRoleDO> userOrgRoleDOList) {
        List<UserOrgRoleDTO> existList = userOrgRoleMapper.listOrgRoleByUserId(userId);
        // 增加不存在的
        for (UserOrgRoleDO itemDO : userOrgRoleDOList) {
            boolean exist = false;
            for (UserOrgRoleDTO itemDTO : existList) {
                if (this.isSame(itemDO, itemDTO)) {
                    exist = true;
                    break;
                }
            }
            if (exist) {
                continue;
            }
            itemDO.setCreator(userId);
            userOrgRoleMapper.insert(itemDO);
        }
        // 删除多余的
        for (UserOrgRoleDTO itemDTO : existList) {
            boolean exist = false;
            for (UserOrgRoleDO itemDO : userOrgRoleDOList) {
                if (this.isSame(itemDO, itemDTO)) {
                    exist = true;
                }
            }
            if (exist) {
                continue;
            }
            userOrgRoleMapper.deleteById(itemDTO.getUserOrgRoleId());
        }
    }

    private boolean isSame(UserOrgRoleDO userOrgRoleDO, UserOrgRoleDTO userOrgRoleDTO) {
        return ObjectUtils.nullSafeEquals(userOrgRoleDO.getOrgId(), userOrgRoleDTO.getOrgId())
                && ObjectUtils.nullSafeEquals(userOrgRoleDO.getRoleId(), userOrgRoleDTO.getRoleId());
    }
}
